<template>
  <div class="app-container">
    <!-- 搜索和添加区域 -->
    <div class="header-bar">
      <el-input
          v-model="searchText"
          placeholder="搜索链接或说明"
          prefix-icon="Search"
          clearable
          @input="filterLinks"
          style="width: 300px; margin-right: 15px"
      />
      <el-button
          type="primary"
          icon="Plus"
          @click="openDialog('add')"
      >
        添加链接
      </el-button>
    </div>

    <!-- 链接表格展示 -->
    <el-table
        :data="filteredLinks"
        stripe
        border
        v-loading="loading"
        style="width: 100%; margin-top: 20px"
        empty-text="暂无链接数据"
    >
      <el-table-column prop="name" label="链接名称" width="180"/>
      <el-table-column prop="url" label="帆软链接">
        <template #default="{ row }">
          <el-link
              type="primary"
              :href="row.url"
              target="_blank"
              @click.prevent="openLink(row.url)"
          >
            {{ row.url }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="链接说明"/>
      <el-table-column label="操作" width="180" align="center">
        <template #default="{ row, $index }">
          <el-button size="small" icon="Edit" @click="openDialog('edit', row, $index)">编辑</el-button>
          <el-button size="small" icon="Delete" type="danger" @click="deleteLink($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
        :title="dialogType === 'add' ? '添加链接' : '编辑链接'"
        v-model="dialogVisible"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="80px"
      >
        <el-form-item label="链接名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入链接名称"/>
        </el-form-item>
        <el-form-item label="帆软链接" prop="url">
          <el-input
              v-model="formData.url"
              placeholder="请输入帆软链接"
              @blur="formatUrl"
          />
        </el-form-item>
        <el-form-item label="链接说明" prop="description">
          <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入链接说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from "../../utils/request.js";
import {useLoading} from '../../utils/loading'

const url = {
  addLinkUrl: '/fanruanLink/addLink',
  searchUrl: '/fanruanLink/search',
  updateLinkUrl: '/fanruanLink/updateLink',
  deleteUrl: '/fanruanLink/delete',
}


const loading = ref(false)
// 链接数据
const links = ref([])

// 搜索相关
const searchText = ref('')
const filteredLinks = ref([...links.value])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const currentIndex = ref(null)

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  url: '',
  description: ''
})

// 表单验证规则
const formRules = reactive({
  name: [
    {required: true, message: '请输入链接名称', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur'}
  ],
  url: [
    {required: true, message: '请输入帆软链接', trigger: 'blur'},
    {pattern: /^https?:\/\/.+\..+$/, message: '请输入有效的URL', trigger: 'blur'}
  ],
  description: [
    {max: 100, message: '描述不能超过100个字符', trigger: 'blur'}
  ]
})

// 加载本地存储的数据
onMounted(() => {
  httpSearch()
})

// 过滤链接
const filterLinks = () => {
  if (!searchText.value) {
    filteredLinks.value = [...links.value]
    return
  }

  const searchLower = searchText.value.toLowerCase()
  filteredLinks.value = links.value.filter(link =>
      link.name.toLowerCase().includes(searchLower) ||
      link.description.toLowerCase().includes(searchLower) ||
      link.url.toLowerCase().includes(searchLower)
  )
}

// 打开对话框
const openDialog = (type, row = null, index = null) => {
  dialogType.value = type
  currentIndex.value = index

  if (type === 'edit' && row) {
    Object.assign(formData, {...row})
  } else {
    resetFormData()
  }

  dialogVisible.value = true
}

// 重置表单数据
const resetFormData = () => {
  formData.id = null
  formData.name = ''
  formData.url = ''
  formData.description = ''
}

// 格式化URL
const formatUrl = () => {
  if (formData.url && !formData.url.startsWith('http')) {
    formData.url = 'https://' + formData.url
  }
}

const httpAddLink = (newLink) => {
  const loading = useLoading()
  request({
    url: url.addLinkUrl,
    method: 'post',
    data: newLink
  }).then(res => {
    if (res.code == 200) {
      httpSearch()
      ElMessage.success('链接添加成功')
      return
    }
    ElMessage.warning(res.message)
  }).finally(() => {
    loading.close();
  })
}

const httpUpdateLink = () => {
  const loading = useLoading()
  request({
    url: url.updateLinkUrl,
    method: 'put',
    data: formData
  }).then(res => {
    if (res.code == 200) {
      httpSearch()
      ElMessage.success('链接更新成功')
      return
    }
    ElMessage.warning(res.message)
  }).finally(() => {
    loading.close();
  })
}
const httpSearch = () => {
  loading.value = true
  request({
    url: url.searchUrl,
    method: 'get',
    params: {
      keyword: searchText.value
    }
  }).then(res => {
    if (res.code == 200) {
      links.value = res.data
      filterLinks()
      return
    }
    ElMessage.warning(res.message)
  }).finally(() => {
    loading.value = false
  })
}
const httpDelete = (index) => {
  let link = links.value[index]
  const loading = useLoading()
  request({
    url: url.deleteUrl + "/" + link.id,
    method: 'delete',
  }).then(res => {
    if (res.code == 200) {
      httpSearch()
      ElMessage.success('链接已删除')
      return
    }
    ElMessage.warning(res.message)
  }).finally(() => {
    loading.close();
  })
}
// 提交表单
const submitForm = () => {
  if (!formData.name || !formData.url) {
    ElMessage.warning('请填写必填项')
    return
  }

  if (dialogType.value === 'add') {
    // 添加新链接
    const newLink = {
      id: Date.now(),
      ...formData
    }
    httpAddLink(newLink)
  } else if (currentIndex.value !== null) {
    httpUpdateLink()
    // 更新现有链接
  }

  // 保存到本地存储
  localStorage.setItem('fanruanLinks', JSON.stringify(links.value))

  dialogVisible.value = false
  filterLinks()
}

// 删除链接
const deleteLink = (index) => {
  ElMessageBox.confirm('确定要删除此链接吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    httpDelete(index)
  }).catch(() => {
  })
}

// 打开链接（添加安全控制）
const openLink = (url) => {
  // if (url.startsWith('https://report.example.com')) {
  window.open(url, '_blank')
  // } else {
  //   ElMessage.warning('仅允许访问帆软报表链接')
  // }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  /*background-color: #f5f7fa;*/
  height: calc(100vh - 98px);
}

.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.el-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  overflow: hidden;
}

.el-link {
  font-weight: normal;
}
</style>
